package com.mr.service.impl;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.web.context.WebApplicationContext;

import com.mr.dao.Dao;
import com.mr.service.BaseService;

public class BaseServiceImpl implements BaseService{

   protected WebApplicationContext applicationContext;
   @Autowired@Qualifier("baseDao")
   protected Dao baseDao;
   @Autowired@Qualifier("hibernateTemplate")
   protected HibernateTemplate hibernateTemplate;
   @Autowired@Qualifier("jdbcTemplate")
   protected JdbcTemplate jdbcTemplate;
   public void setJdbcTemplate(JdbcTemplate template){
      jdbcTemplate = template;
   }
   public void setHibernateTemplate(HibernateTemplate hbt) {
      hibernateTemplate = hbt;
   }
	public JdbcTemplate getJdbcTemplate() {
      return jdbcTemplate;
   }
   
   public void setApplicationContext(ApplicationContext ctx){
      applicationContext = (WebApplicationContext)ctx;
   }
   public String getContextPath(){
      return getRealPath("/");
   }
   public String getRealPath(String filename){
      return applicationContext.getServletContext().getRealPath(filename);
   }
   public HibernateTemplate getHibernateTemplate() {
      return hibernateTemplate;
   }
  
   
   public Dao getBaseDao() {
      return baseDao;
   }
   public void setBaseDao(Dao baseDao) {
      this.baseDao = baseDao;
   }
	
	public  List pageQuery(final String hql,final Integer page,final Integer size,final Object...o){
		return hibernateTemplate.executeFind(new HibernateCallback(){
			
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query=session.createQuery(hql);
				if(page!=null&&size!=null)
					query.setFirstResult((page-1)*size).setMaxResults(size);
				if(o!=null)
					for (int i = 0; i < o.length; i++) {
						query.setParameter(i, o[i]);
					}
				return query.list();
			}});
	}
}